/*
 * Copyright (c) 2010. Dylan Schell.
 */

package nl.xs4all.dylanschell.deckprinter.pages;

import com.google.inject.Inject;
import nl.xs4all.dylanschell.deckprinter.model.CardInSet;
import nl.xs4all.dylanschell.deckprinter.services.ImageService;
import org.apache.wicket.injection.web.InjectorHolder;
import org.apache.wicket.markup.html.WebResource;
import org.apache.wicket.util.resource.AbstractResourceStream;
import org.apache.wicket.util.resource.IResourceStream;
import org.apache.wicket.util.resource.ResourceStreamNotFoundException;
import org.apache.wicket.util.time.Time;
import org.apache.wicket.util.value.ValueMap;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

public class CardImageResource extends WebResource
{
    @Inject
    public ImageService imageService;

    public CardImageResource()
    {
        InjectorHolder.getInjector().inject(this);

    }

    @Override
    public IResourceStream getResourceStream()
    {
        ValueMap parameters = getParameters();
        String set = parameters.getString("set");
        String card = parameters.getString("card");
        UUID setId = UUID.fromString(set);
        UUID cardId = UUID.fromString(card);
        final CardInSet cis = new CardInSet(cardId, setId, null);
        return new AbstractResourceStream()
        {
            public InputStream getInputStream() throws ResourceStreamNotFoundException
            {
                final byte[] bytes = imageService.getImage(cis);
                return new ByteArrayInputStream(bytes);
            }

            public void close() throws IOException
            {

            }

            @Override
            public String getContentType()
            {
                return "image/jpeg";
            }

            @Override
            public Time lastModifiedTime()
            {
                long lastModified = imageService.getLastModified(cis);
                return Time.valueOf(lastModified);
            }
        };
    }


}
